package com.tdf.lolpanel.service.impl;

import com.tdf.lolpanel.constant.JwtConstant;
import com.tdf.lolpanel.constant.MsgConstant;
import com.tdf.lolpanel.context.BaseContext;
import com.tdf.lolpanel.dto.UserLoginDTO;
import com.tdf.lolpanel.dto.UserRegisterDTO;
import com.tdf.lolpanel.entity.User;
import com.tdf.lolpanel.mapper.UserMapper;
import com.tdf.lolpanel.service.UserService;
import com.tdf.lolpanel.constant.StatusConstant;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户登录
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        // 1. 根据用户名查询数据库中的数据
        User user = userMapper.getByUsername(username);

        // 2. 处理异常情况
        if (user == null) {
            // 账号不存在
            throw new IllegalStateException(MsgConstant.ACCOUNT_NOT_FOUND);
        }

        // 密码比对
        if (!user.getPassword().equals(password)) {
            // 密码错误
            throw new IllegalStateException(MsgConstant.PASSWORD_ERROR);
        }

        if (user.getStatus().equals(StatusConstant.USR_DISABLE)) {
            // 账号禁用
            throw new IllegalStateException(MsgConstant.ACCOUNT_LOCKED);
        }

        // 写入Redis
        redisTemplate.opsForValue().set("jwt_" + user.getId(), 1);

        return user;
    }

    /**
     * 添加用户
     */
    @Override
    public void add(UserRegisterDTO userRegisterDTO) {
        User user = new User();

        // 对象属性拷贝
//        BeanUtils.copyProperties(userRegisterDTO, user);
        user.setUsername(userRegisterDTO.getUsername());
        user.setLolname(userRegisterDTO.getLolname());
        user.setPhone(userRegisterDTO.getPhone());

        // 设置其他参数
        user.setStatus(StatusConstant.USR_USER);

        // 设置密码，此处可以md5加密
        user.setPassword(userRegisterDTO.getPassword());
//        user.setPassword(DigestUtils.md5DigestAsHex(userRegisterDTO.getPassword().getBytes()));

        // 设置记录时间和修改时间
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());

        // 数据库操作
        userMapper.insert(user);
    }

    /**
     * 退出登录
     */
    @Override
    public void logout(Integer uid) {
        if (redisTemplate.opsForValue().get("jwt_" + uid) != null) {
            redisTemplate.delete("jwt_" + uid);
        }
    }
}
